﻿using System.Collections.Generic;
using System.Linq;

namespace Silent.Data.Memento
{
    public class Memento<T> : IMemento<T> where T : new()
    {
        protected Stack<T> instances = new Stack<T>();
        public ICloneStrategy<T> CloneStrategy { get; set; }

        public Memento(T original)
        {
            instances.Push(original);
        }
        public Memento() : this(new T())
        {
        }
        public T Current
        {
            get { return instances.Last(); }
        }

        public virtual T Create()
        {
            return CloneStrategy == null ? new T() : CloneStrategy.Clone(Current);
        }
        public virtual void Apply(T instance)
        {
            instances.Push(instance);
        }
        public virtual T Revert()
        {
            if (instances.Count > 1)
                instances.Pop();
            return Current;
        }
        public virtual void Reset()
        {
            T first = instances.Pop();
            instances.Clear();
            instances.Push(first);
        }
    }
}